import React, { useState } from 'react';
import BreadCrumb from '@/components/BreadCrumb';
import s from './style.module.less';
import { Anchor, Message, Loading, Button, Confirm } from '@knownsec/react-component';
import LoadingCom from '@/components/Loading';
import { vulParams, eventSeverityOption } from '../../columns';
import moment from 'moment';
import cn from 'classnames';
import { useLocation, useHistory, Link as RouterLink } from 'react-router-dom';
import { GetQueryString, base64Decode } from '@/common/constant';
import { getGroupResult, eventBatch, vildVul } from '~/API';
const { Link } = Anchor;
const eventSeverityDict ={}
for (const item of eventSeverityOption) {
  eventSeverityDict[item.value] = item.label
}
const info=localStorage.info?JSON.parse(localStorage.info).modules:[]
export default function Vuldetail() {
  const search = useLocation().search;
  const id = GetQueryString(search, 'id');
  const tid = GetQueryString(search, 'tid');
  const type = GetQueryString(search, 'type');
  const vild = GetQueryString(search, 'vild');
  const sid = GetQueryString(search, 'sid');
  const rowSid = GetQueryString(search, 'rowSid');
  const backparam = GetQueryString(search, 'back');
  const [data, setData] = useState({});
  const [detail, setDetail] = useState({});
  const [loading, setLoading] = useState(true);
  const [isVild, setVild] = useState(vild);

  let breadArr = [
    { link: '/', name: '监测列表' },
    {
      link: {
        pathname: '/dashboard',
        search: `id=${tid}&filter=${encodeURI(backparam)}`,
      },
      name: '结果详情',
    },
    { link: '', name: isVild ? '验证详情' : '漏洞详情', active: true },
  ];
  if (sid && sid !== 'undefined' && sid !== 'null') {
    breadArr = [
      { link: '/', name: '监测列表' },
      {
        link: { pathname: '/dashboard', search: `id=${tid}&sid=${sid}&type=${type}&filter=${encodeURI(backparam)}` },
        name: '结果详情',
      },
      { link: '', name: isVild ? '验证详情' : '漏洞详情', active: true },
    ];
  }
  function handleAnchorClick(e) {
    e.preventDefault();
  }
  const getData = () => {
    if (id && rowSid) {
        getGroupResult({ id: rowSid, data: { event_id: id } }).then((res) => {
        if (res.status === 'success') {
          let r = res.data?.data?.events[0] || {};
        //   if (isVild) {
        //     r.detail = r.action.verification_detail || {};
        //   }
          setData(r);
          const tra = r?.detail?.traffics;
          let traffics = {};
          for (let index = tra.length - 1; index >= 0; index--) {
            const item = tra[index] || {};
            if (JSON.stringify(item.request) !== '{}' && JSON.stringify(item.response) !== '{}') {
              traffics = item;
              break;
            }
          }
          const d = {
            name: r?.detail.name?.zh_cn || '-',
            type: r?.detail?.vuln_type?.map((item) => item.zh_cn).join('、') || '-',
            severity: eventSeverityDict[r?.severity_name] || '-',
            time: '-',
            source: r?.detail?.source || '-',
            code: r?.detail?.cve.join('、') || '-',
            traffics,
          };
          setDetail(d);
        }
        setLoading(false);
      });
    } else {
      return Message.show({
        pro: true,
        type: 'error',
        message: '信息缺失',
        showClose: false,
      });
    }
  };
  const confirmVild = (a) => {
    Confirm({
      pro: true,
      title: '确认提示',
      message: <div className="confirmbox">确认要验证该地址吗？</div>,
      onconfirm: () => {
        if (a == 1) {
          vildVulStatus();
        } else {
          fixStatus(a);
        }
      },
      oncancel: () => {},
    });
  };
  const vildVulStatus = () => {
    vildVul({ event_id: id }).then((res) => {
      if (res.status === 'success') {
        getData();
        Message.show({
          pro: true,
          type: 'success',
          message: '操作成功',
          showClose: false,
        });
      }
    });
  };
  const request = () => {
    const traffics = detail.traffics;
    let url = '/';
    if (traffics?.request?.url) {
      let url_ = traffics?.request?.url.replace('//', '/').split('/');
      url_.splice(0, 2);
      url_ = url_.join('/');
      url = '/' + url_;
    }
    let request = JSON.stringify(traffics?.request?.headers || {})
      .replace(/^\{(.*)\}$/g, '$1')
      .replace(/,"/g, ',')
      .replace(/":/g, ': ')
      .replace(/",/g, '"\n')
      .replace(/"/g, '');
      if (traffics?.request?.method && traffics?.response?.version) {
				request =
					`${traffics?.request?.method} ${url} ${traffics?.response?.version}\n` +
					request;
			}
    request = request.replace(/",/g, '"\n');
    (!request || request.includes('undefined')) && (request = '--');
    try {
      request = `${request}\n\n${base64Decode(traffics?.request?.b64content)}`;
    } catch (error) {
      request = `${request}\n\n${traffics?.request?.b64content}`;
      console.log('traffics?.request?.b64content编码有误');
    }
    return request;
  };
  const response = () => {
    const traffics = detail.traffics;

    const { headers } = traffics?.response || {};
    let response = JSON.stringify(headers || {})
      .replace(/^\{(.*)\}$/g, '$1')
      .replace(/,"/g, ',')
      .replace(/":/g, ': ');
      if (traffics?.response?.version && traffics?.response?.status_code) {
				response =
					`${traffics?.response?.version} ${traffics?.response?.status_code}\n` +
					response;
			}
    response = response.replace(/",/g, '"\n').replace(/"/g, '');
    try {
      response = `${response && response + '\n\n'}${base64Decode(traffics?.response?.b64content)}`;
    } catch (error) {
        response = `${response}\n\n${traffics?.response?.b64content}`;
      console.log('traffics?.response?.b64content编码有误');
    }
    response.includes('undefined') && (response = '--');
    return response;
  };
  const vildDate = (item) => {
    if (isVild) {
      return (
        <>
          验证时间：
          <span>
            {data?.action?.verification_detail?.found_at
              ? moment(data.action.verification_detail.found_at).format('YYYY-MM-DD HH:mm:ss')
              : '-'}
          </span>
        </>
      );
    } else {
      return (
        <>
          发现时间：
          <span>
            {data?.detail?.found_at
              ? moment(data.detail.found_at).format('YYYY-MM-DD HH:mm:ss')
              : '-'}
          </span>
        </>
      );
    }
  };
  function fixStatus(type) {
    const data = { event_ids: [id], verification: type };
    eventBatch(data).then((res) => {
      if (res.status === 'success') {
        getData();
        Message.show({
          pro: true,
          type: 'success',
          message: '操作成功',
          showClose: false,
        });
      }
    });
  }
  React.useMemo(() => {
    getData();
  }, [id, isVild]);
  return (
    <>
      <BreadCrumb arr={breadArr} />
      <div id="vul" className={s.vuldetail}>
        <Loading show={loading} />
        <div className={s.title}>漏洞详情</div>
        <div className={s.paramsbox}>
          {vulParams.map((item) => {
            let dom = null;
            if (item.key === 'time') {
              dom = (
                <div key={item.key} className={cn(s.item, s[item.className])}>
                  {vildDate()}
                </div>
              );
            } else if (item.key === 'name') {
              dom = (
                <div key={item.key} className={cn(s.item, s[item.className])}>
                  {item.name}：{' '}
                  <RouterLink
                    className={s.linkStyle}
                    to={{
                      pathname: `/bug_store`,
                      search: `name=${encodeURI(detail[item.key])}`,
                    }}
                  >
                    {detail[item.key] || '-'}
                  </RouterLink>
                </div>
              );
            } else {
              dom = (
                <div key={item.key} className={cn(s.item, s[item.className])}>
                  {item.name}： <span>{detail[item.key] || '-'}</span>
                </div>
              );
            }
            return dom;
          })}
        </div>
        {isVild ? null : (
          <div className={s.vildbtn}>
            {data?.action?.verification||!info.includes('vul_verification_task') ? null : (
              <Button pro type="primary" className={s.button} onClick={() => confirmVild(1)}>
                <span className={s.linkSpan}>验证</span>
              </Button>
            )}
            {data?.action?.verification == 1 && (
              <Button pro type="primary" className={s.button}>
                <span className={s.linkSpan}>
                  验证中 <LoadingCom color="#fff" />
                </span>
              </Button>
            )}
            {data?.action?.verification > 1 && data.action.verification != 4 && (
              <>
                <Button pro type="primary" className={s.button} onClick={() => confirmVild(4)}>
                  <span className={s.linkSpan}>再次验证</span>
                </Button>
                <br />
                {/* <Button style={{marginTop: 10}} pro className={s.button} onClick={() => confirmVild(3)}>
                <span className={s.linkSpan}>验证误报</span>
              </Button> */}
              </>
            )}
            {data?.action?.verification > 1 && data.action.verification != 3 && (
              <>
                <Button
                  style={{ marginTop: 10 }}
                  pro
                  className={s.button}
                  onClick={() => confirmVild(3)}
                >
                  <span className={s.linkSpan}>验证误报</span>
                </Button>
              </>
            )}
            {data?.action?.verification > 1 && data.action.verification != 3 && (
              <>
                <a
                  href={`/#/vul_detail/?id=${id}&tid=${tid}&type=vul&vild=true&sid=${sid}&rowSid=${data.task_session_id}`}
                  target='_blank'
                //   onClick={() => setVild(true)}
                  style={{
                    textAlign: 'center',
                    cursor: 'pointer',
                    color: '#0b6fd6',
                    marginTop: 10,
                    display: 'block',
                    userSelect: 'none',
                  }}
                >
                  查看验证结果
                </a>
              </>
            )}
          </div>
        )}
        <div className={s.vulbox}>
          <Anchor
            className={s.anchoritem}
            onClick={handleAnchorClick}
            getContainer={() => document.getElementById('vul')}
          >
            <Link href="#desc" title="漏洞描述" />
            <Link href="#risk-url" title="风险地址" />
            <Link href="#req-info" title="请求信息" />
            <Link href="#res-info" title="响应信息" />
            <Link href="#payload" title="payload" />
            <Link href="#vul-info" title="漏洞详情" />
            <Link href="#vul-eff" title="漏洞影响" />
            <Link href="#fix-adv" title="修复建议" />
            <Link href="#show-info" title="参考信息" />
          </Anchor>
          <div className={s.detailbox}>
            <div id="desc" className={s.title}>
              漏洞描述
            </div>
            <div className={s.detailitem}>{data?.detail?.description.zh_cn || '-'}</div>
            <div id="risk-url" className={s.title}>
              风险地址
            </div>
            <div className={cn(s.detailitem, s.redstyle)}>{data?.detail?.url || '-'}</div>
            <div id="req-info" className={s.title}>
              请求信息
            </div>
            <div className={s.detailitem}>
              <pre className={s.pre}>{request()}</pre>
            </div>
            <div id="res-info" className={s.title}>
              响应信息
            </div>
            <div className={s.detailitem}>
              <pre className={s.pre}>{response()}</pre>
            </div>
            <div id="payload" className={s.title}>
              payload
            </div>
            <div className={s.detailitem}>{data?.detail?.payload || '-'}</div>
            <div id="vul-info" className={s.title}>
              漏洞详情
            </div>
            <div className={s.detailitem}>{data?.detail?.extra_details?.zh_cn || data?.detail?.extra_detail||'-'}</div>
            <div id="vul-eff" className={s.title}>
              漏洞影响
            </div>
            <div className={cn(s.detailitem, s.redstyle)}>{data?.detail?.impact.zh_cn || '-'}</div>
            <div id="fix-adv" className={s.title}>
              修复建议
            </div>
            <div className={cn(s.detailitem, s.greenstyle)}>
              {data?.detail?.recommendation.zh_cn || '-'}
            </div>
            <div id="show-info" className={s.title}>
              参考信息
            </div>
            <div className={s.detailitem}>
              {data?.detail?.reference && data.detail.reference.length
                ? data.detail.reference.map((item) => (
                    <a target="_blank" href={item}>
                      {item}
                    </a>
                  ))
                : '-'}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
